package cc.rengu.oltp.utility.util;

import cc.rengu.utility.cache.UnifiedCacheNode;
import cc.rengu.utility.threadarea.ThreadVar;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 交易全局缓存工具类
 * Created by wangcheng on 2021/3/26 18:05
 */
public class GlobalTransUtil implements Serializable {
    /**
     * 设置name节点值为value的对象设置到交易全局缓存中
     *
     * @param key   节点KEY
     * @param value 节点VALUE
     */
    public static void setCacheValue(String key, Object value) throws Exception {
        if (StringUtil.isEmptyOrNull(key) || null == value) {
            throw new Exception("交易全局缓存设置KE或者VALUE为空!");
        } else {
            UnifiedCacheNode transCacheNode = (UnifiedCacheNode) ThreadVar.getVar("_IGAS_TRANSACTION_CACHE_");
            if (null == transCacheNode) {
                transCacheNode = new UnifiedCacheNode();
                transCacheNode.set(key, value);
                ThreadVar.setVar("_IGAS_TRANSACTION_CACHE_", transCacheNode);
            } else {
                transCacheNode.set(key, value);
            }
        }
    }

    /**
     * 从交易全局缓存中取节点KEY为name的值
     *
     * @param key 节点KEY
     * @return 节点VALUE
     */
    public static Object getCacheValue(String key) {
        UnifiedCacheNode transCacheNode = (UnifiedCacheNode) ThreadVar.getVar("_IGAS_TRANSACTION_CACHE_");
        if (null == transCacheNode) {
            return null;
        } else {
            return transCacheNode.get(key);
        }
    }

    /**
     * 交易缓存数据清理
     */
    public static void clearCacheValue() {
        UnifiedCacheNode transCacheNode = (UnifiedCacheNode) ThreadVar.getVar("_IGAS_TRANSACTION_CACHE_");
        if (null != transCacheNode) {
            transCacheNode.clear();
        }
    }

    /**
     * 将交易全局缓存中删除节点KEY为name的值
     *
     * @param key 节点KEY
     */
    public static void removeCacheValue(String key) {
        UnifiedCacheNode transCacheNode = (UnifiedCacheNode) ThreadVar.getVar("_IGAS_TRANSACTION_CACHE_");
        if (null != transCacheNode) {
            transCacheNode.remove(key);
        }
    }

    /**
     * 获取交易所有全局缓存
     *
     * @return 交易所有全局缓存
     */
    public ConcurrentHashMap<String, Object> getTransCache() {
        UnifiedCacheNode transCacheNode = (UnifiedCacheNode) ThreadVar.getVar("_IGAS_TRANSACTION_CACHE_");
        if (null != transCacheNode) {
            return transCacheNode.list();
        }
        return null;
    }
}
